<template>
	<div class="layout-padding" v-loading="printing">
		<div class="layout-padding-auto layout-padding-view" style="overflow: auto">
			<el-row v-show="showSearch" style="width: 100%; text-align: right">
				<div style="font-size: 18px; font-weight: 700">项目复盘分析</div>
				<el-form :model="queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList" style="width: 100%">
					<el-form-item label="项目名称" prop="name">
						<el-select v-model="queryForm.projectIds" multiple placeholder="请选择项目名称" @change="handleProjectChange" clearable>
							<el-option :key="index" :label="item.name" :value="item.id" v-for="(item, index) in projectData" />
						</el-select>
					</el-form-item>
					<el-form-item label="月份" prop="yearMonths">
						<el-select v-model="queryForm.yearMonths" multiple placeholder="请选择年份" @change="getDataList" clearable>
							<el-option :key="index" :label="item.yearMonth" :value="item.yearMonth" v-for="(item, index) in monthData" />
						</el-select>
					</el-form-item>
					<el-form-item label="成本项" prop="costTypeIds">
						<el-select v-model="queryForm.costTypeIds" multiple placeholder="请选择月份" @change="getDataList" clearable>
							<el-option :key="index" :label="item.name" :value="item.id" v-for="(item, index) in costTypeData" />
						</el-select>
					</el-form-item>
				</el-form>
			</el-row>
			<div ref="captureRef">
				<el-row v-show="showInfo">
					<el-card class="relative w-full h-full">
						<el-descriptions :column="4" border>
							<div :key="index" v-for="(item, index) in projectInfos">
								<el-descriptions-item label="年度">{{ new Date(item.createTime).getFullYear() }}</el-descriptions-item>
								<el-descriptions-item label="项目名称">{{ item.name }}</el-descriptions-item>
								<el-descriptions-item label="合同金额">{{ item.contractAmount.toFixed(2) }}元</el-descriptions-item>
								<el-descriptions-item label="利润率">{{ item.profitRate }}%</el-descriptions-item>
							</div>
						</el-descriptions>
					</el-card>
				</el-row>
				<el-row v-show="showChart">
					<el-card class="relative w-full mt-10">
						<v-chart ref="chartRef" class="w-full" style="height: 600px" autoresize />
					</el-card>
				</el-row>
				<el-row>
					<el-card class="relative w-full mt-10">
						<el-input type="textarea" rows="5" v-model="queryForm.remark" placeholder="备注" />
					</el-card>
				</el-row>
			</div>
			<el-row>
				<div class="mb8" style="width: 100%; text-align: right">
					<!-- 触发按钮 -->
					<el-button type="primary" class="m-10" @click="handlePrint">打印</el-button>
				</div>
			</el-row>
			<!-- 隐藏的打印容器 -->
			<div id="printContainer" class="only-print">
				<img :src="imageUrl" class="print-image" />
			</div>
		</div>
	</div>
</template>

<script setup lang="ts" name="internalReplayAnalysis">
import VChart from 'vue-echarts';
import { use } from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { TooltipComponent, LegendComponent, ToolboxComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
use([TooltipComponent, LegendComponent, CanvasRenderer, ToolboxComponent, GridComponent, BarChart]);
import { projectList, expectList, costTypeList } from '/@/api/internal/cost/intProject';
import { getReplayData } from '/@/api/internal/cost/intProjectAnalysis';
import { computed } from 'vue';
import html2canvas from 'html2canvas';
import printJS from 'print-js';

const printing = ref(false); // 表格遮罩层
const showSearch = ref(true);
const showInfo = ref(true);
const showChart = ref(true);

// 定义变量内容
const projectData = ref<any[]>([]); // 项目列表
const monthData = ref<any[]>([]); // 月份列表
const costTypeData = ref<any[]>([]); // 成本项列表

// 查询参数
const queryForm = reactive({
	projectIds: ref<any[]>([]),
	yearMonths: ref<any[]>([]),
	costTypeIds: ref<any[]>([]),
	remark: '',
});

const getCostTypeData = () => {
	costTypeList({ projectIds: queryForm.projectIds }).then((res) => {
		costTypeData.value = res.data;
	});
};

const getExpectData = () => {
	expectList({ projectIds: queryForm.projectIds }).then((res) => {
		monthData.value = res.data;
	});
};

// 获取项目列表数据
const getProjectData = () => {
	projectList().then((res) => {
		projectData.value = res.data;
		queryForm.projectIds.push(projectData.value[0].id);
		getDataList();
		getExpectData();
		getCostTypeData();
	});
};

getProjectData();

const projectInfos = computed(() => {
	if (queryForm.projectIds && queryForm.projectIds.length > 0)
		return projectData.value.filter((item) => queryForm.projectIds.indexOf(item.id) !== -1);
	else return projectData.value;
});

// 元素引用
const captureRef = ref<HTMLElement | null>(null);
const imageUrl = ref<string>('');

const generatePrintImage = async () => {
	if (!captureRef.value) return;

	try {
		// 配置选项（可选）
		const options: html2canvas.Options = {
			scale: 4, // 缩放比例
			useCORS: true, // 允许跨域图片
			logging: true, // 调试日志
			backgroundColor: '#FFFFFF',
		};

		// 生成 canvas
		const canvas = await html2canvas(captureRef.value, options);

		// 转换为图片 URL
		const imageData = canvas.toDataURL('image/png');
		imageUrl.value = imageData;
	} catch (error) {
		console.error('截图失败:', error);
	}
};

const labelOption = {
	show: true,
	rotate: 0,
	align: 'center',
	verticalAlign: 'middle',
	position: 'top',
	distance: 15,
	formatter: (params: any) => {
		return (params.data.ratio ? params.data.ratio + '%' : '') + '\n' + params.data.value;
	},
	fontSize: 16,
	rich: {
		name: {},
	},
};

const legendData = ref<any[]>([]);

const axisData = ref<any[]>([]);

const seriesData = ref<any[]>([]);

const grid = {
	left: 100,
	right: 100,
	top: 50,
	bottom: 0,
	containLabel: true, // 确保标签不被裁剪
};
const getSeriesConfig = () => {
	return legendData.value.map((name, sid) => {
		return {
			name,
			type: 'bar',
			barGap: 0,
			label: labelOption,
			emphasis: {
				focus: 'series',
			},
			data: seriesData.value[sid],
		};
	});
};

const option = reactive({
	tooltip: {
		trigger: 'axis',
		axisPointer: {
			type: 'shadow',
		},
	},
	legend: {
		data: legendData,
	},
	grid,
	toolbox: {
		show: false,
		orient: 'vertical',
		left: 'right',
		top: 'center',
		feature: {
			mark: { show: true },
			dataView: { show: true, readOnly: false },
			magicType: { show: true, type: ['line', 'bar', 'stack'] },
			restore: { show: true },
			saveAsImage: { show: true },
		},
	},
	xAxis: [
		{
			type: 'category',
			axisTick: { show: false },
			data: axisData.value,
			axisLabel: {
				interval: 0,
				rotate: 30,

				// formatter: function (value: any) {
				// 	return value.split('').join('\n');
				// },
			},
		},
	],
	yAxis: [
		{
			type: 'value',
			name: '单位（万元）',
			nameTextStyle: {
				color: '#aaa',
				nameLocation: 'start',
			},
		},
	],
	series: [],
});

const chartRef = ref<typeof VChart | null>(null); // 定义 chart 的引用
// 获取项目复盘分析数据
const getDataList = async () => {
	getReplayData(queryForm).then((res) => {
		const costProjectDatas = res.data.costProjectDatas;
		const costTypeDatas = res.data.costTypeDatas;
		const costList = res.data.costList;

		const legendParams = [];
		const axisParams = [];
		const axisIds = [];
		const replayDatas = [];
		for (let i = 0; i < costProjectDatas.length; i++) {
			const project = costProjectDatas[i];
			legendParams.push(project.projectName);

			const costTypeReplayDatas = [];
			for (let j = 0; j < costTypeDatas.length; j++) {
				const costType = costTypeDatas[j];
				if (axisIds.indexOf(costType.costTypeId) == -1) {
					axisIds.push(costType.costTypeId);
					axisParams.push(costType.costTypeName);
				}
				// costTypeReplayDatas.push(costType.amount);
				const obj = costList.filter((item: any) => item.projectId == project.projectId && item.costTypeId == costType.costTypeId)[0];
				costTypeReplayDatas.push({
					value: obj && obj.amount ? (obj.amount / 10000).toFixed(2) : 0,
					ratio: obj ? obj.ratio?.toFixed(2) : null,
					costActual: obj && obj.amount ? obj.amount : 0,
				});
			}
			replayDatas.push(costTypeReplayDatas);
		}
		legendData.value = legendParams;
		option.xAxis[0].data = axisParams;
		seriesData.value = replayDatas;
		option.series = getSeriesConfig();
		chartRef.value.setOption(option, true); // 手动更新图表
		chartRef.value.resize();
	});
};

const handleProjectChange = async () => {
	queryForm.yearMonths.length = 0;
	queryForm.costTypeIds.length = 0;
	getDataList();
	getExpectData();
	getCostTypeData();
};
const handlePrint = () => {
	printing.value = true;
	nextTick(() => {
		generatePrintImage();
		setTimeout(() => {
			printing.value = false;
			printJS({
				printable: [imageUrl.value], // 提取 URL 数组
				type: 'image',
				header: '',
				style: '@media print { body { margin: 0; } #printSection { margin-top: 0; } img { max-width: 100%; page-break-inside: avoid; } }', // 内联CSS样式
				imageStyle: 'width: 100%; margin: 10px auto; page-break-after: always;', // 分页关键
			});
		}, 5000);
	});
};
</script>
<style scoped>
/* 隐藏打印容器的优化方案 */
.only-print {
	display: none;
}

/* 打印时的图片样式 */
@media print {
	.print-image {
		width: 100% !important;
		height: auto !important;
		page-break-after: always; /* 分页控制（可选） */
	}
	.only-print {
		display: block !important; /* 显示仅在打印时可见的内容 */
	}
	@page {
		margin: 10px; /* 去除页边距 */
	}
}
</style>
